<template>
    <a-form ref="formRef" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" @finish="handleFinish">
        <a-row>
            <a-col :span="12">
                <a-form-item label="合同名称" name="name" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.name" style="width: 100%" />
                    <!-- <a-input :disabled="disabled" v-model:value="form.name" style="width: 100%" /> -->
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="合同编号" name="code">
                    <a-input disabled v-model:value="form.code" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>

        <a-row>

            <a-col :span="12">
                <a-form-item label="项目名称" name="proName" :rules="[{ required: true, message: '请选择项目' }]">
                    <a-input-search readonly :disabled="disabled" v-model:value="form.proName" style="width: 100%"
                        placeholder="选择的项目" @click="onSearch" @search="onSearch" />

                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="项目编号" name="proCode" :rules="[{ required: true }]">
                    <a-input disabled v-model:value="form.proCode" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="采购负责人" name="director" :rules="[{ required: true }]">
                    <a-input v-model:value="form.directorName" :disabled="disabled" @click="showUserSelect()"
                        style="width: 100%" placeholder="" />
                </a-form-item>
            </a-col>

        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="供应商" name="supplierName" :rules="[{ required: true, message: '请选择供应商' }]">
                    <a-input-search readonly :disabled="disabled" @click="onSupplier" @search="onSupplier"
                        v-model:value="form.supplierName" style="width: 100%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="签订日期" name="contTime" :rules="[{ required: true }]">
                    <!-- <a-input :disabled="disabled" v-model:value="form.signingDate" style="width: 100%" /> -->
                    <a-date-picker :getCalendarContainer="trigger => trigger.parentNode"
                        valueFormat="YYYY-MM-DD hh:mm:ss" :disabled="disabled" v-model:value="form.contTime"
                        style="width: 100%" />

                </a-form-item>
            </a-col>
        </a-row>
        <a-row>
            <a-col :span="12">
                <a-form-item label="合同金额" name="amount" :rules="[{ required: true }]">
                    <a-input-number :disabled="disabled" v-model:value="form.amount" style="width: 100%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="预算剩余金额" name="budgetRemain" :rules="[{ required: true }]">
                    <a-input :disabled="disabled" v-model:value="form.budgetRemain" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>

        <a-row>
            <a-col :span="12">
                <a-form-item label="累计付款比例" name="payPercent" :rules="[{ required: true }]">
                    <a-input-number :disabled="disabled" v-model:value="form.payPercent" style="width: 100%" :min="0"
                        :step="0.01" addon-after="%" />
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item label="是否收到原件" name="original">

                    <a-radio-group :disabled="disabled" v-model:value="form.original">
                        <a-radio :value="'1'">是</a-radio>
                        <a-radio :value="'0'">否</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-col>
        </a-row>

        <a-row>
            <a-col :span="12">
                <a-form-item label="合同审核稿" name="contractReviewDraft">
                    <fileUpload @uploadDone="uploadDone1" :isShow="disabled" :files="form.files1" ref="uploadRef1"
                        :type="1" :uploadNumber="4"></fileUpload>
                </a-form-item>
            </a-col>
            <a-col :span="12">
                <a-form-item v-show="form.original === '1'" label="合同正本" name="original">
                    <div>
                        <fileUpload @uploadDone="uploadDone2" :isShow="disabled" :files="form.files2" ref="uploadRef2"
                            :type="2" :uploadNumber="4"></fileUpload>
                    </div>
                </a-form-item>
            </a-col>
        </a-row>


        <a-row>
            <a-col :span="24">
                <a-form-item label="备注" name="remark" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
                    <a-textarea :disabled="disabled" v-model:value="form.remark" style="width: 100%" />
                </a-form-item>
            </a-col>
        </a-row>
        <a-row :gutter="16" class="mb-2">

            <a-col :span="6" style="font-weight: 600;">
                采购合同明细：
            </a-col>
            <a-col :span="18" class="text-right" v-if="!isShow">
                <!-- <a-button class="ml-2" @click="addMaterial" type="primary">新增明细</a-button> -->
            </a-col>
        </a-row>
        <a-row :gutter="16">
            <a-col :span="24">
                <a-table :dataSource="form.purMaterialList" bordered :columns="columns" :pagination="false"
                    :scroll="{ x: 1300 }">
                    <template #bodyCell="{ column, record, index }">
                        <template v-if="column.key === 'index'">
                            <div>
                                {{ index + 1 }}
                            </div>
                        </template>
                        <!-- <template v-if="column.key === 'code'">
                            {{ !record.code ? record.material.code : record.code  }}  
                        </template>
                        <template v-if="column.key === 'name'">
                            {{ !record.name ? record.material.name : record.name  }}  
                        </template> -->
                        <template v-if="column.key === 'budgetUnitPrice'">
                            <a-input-number :min="0" :disabled="disabled"
                                v-model:value="record.budgetUnitPrice"></a-input-number>
                        </template>
                        <template v-if="column.key === 'budgetRemain'">
                            <a-input-number :disabled="disabled" :precision="2"
                                v-model:value="record.budgetRemain"></a-input-number>
                        </template>
                        <template v-if="column.key === 'num'">
                            <a-input-number :disabled="disabled" :precision="2"
                                v-model:value="record.num"></a-input-number>
                        </template>
                        <template v-if="column.key === 'total'">
                            {{ record.budgetUnitPrice && record.num ? record.budgetUnitPrice * record.num : 0
                            }}
                        </template>

                    </template>
                </a-table>
            </a-col>
        </a-row>
        <system :value="form"></system>
        <projectSelection ref="proSelect" @onClose="prSelectOk" :value="form.proSelectRecords" />
        <supplierSelection ref="supplierSelect" @onClose="supplierSelectOk" />
        <userSelectorPlus ref="userSelectorRef" @OnClose="userSelectorOk" />
        <materialSelection ref="mSelection" @onClose="mSelectOk" />
    </a-form>
</template>

<script setup>
import api from '@/api/contract/purchase/index'
import costApi from '@/api/pm/cost/index'
import projectSelection from '@/components/pm/projectSelection.vue'
import supplierSelection from '@/components/pm/supplierSelection.vue'
import materialSelection from '@/components/pm/materialSelection.vue'
import userSelectorPlus from '@/components/Selector/userSelectorPlusExtend.vue'
import system from '@/components/Task/system.vue'
import fileUpload from '@/components/JqUpload/index.vue'
const formRef = ref()
const form = ref({})
const isShow = ref(false)
const props = defineProps({
    value: {
        type: Object,
        default: () => { }
    },
    disabled: {
        type: Boolean,
        default: () => false
    }
})

watch(
    () => props.value,
    (newVal, oldVal) => {
        if (newVal) {
            form.value = { ...newVal }
            if (form.value) {
                form.value.files1 = form.value.files?.filter(x => x.type == 1)
                form.value.files2 = form.value.files?.filter(x => x.type == 2);
            }
        }
    },
    { deep: true, immediate: true }
)
const userSelectorRef = ref()
const showUserSelect = () => {
    userSelectorRef.value.show("")
}
const userSelectorOk = (data) => {
    form.value.directorName = data.value.directorName
    form.value.director = data.value.directorId
}
const getData = () => {
    return new Promise((resolve, reject) => {
        formRef.value.validate().then(() => {
            form.value.files = (form.value.files1 ?? []).concat(form.value.files2 ?? [])
            if (form.value.purMaterialList) {
                // form.value.purMaterialList = form.value.purMaterialList.splice(0, form.value.purMaterialList.length - 1)
            }
            form.value.flowCode = "FLW_CONTRACT_PUR"
            resolve(form.value)
        }).catch((err) => {
            reject(err)
        });
    })
}

const uploadDone1 = (result) => {
    console.log("uploadDone1", result)
    form.value.files1 = result
}
const uploadDone2 = (result) => {
    console.log("uploadDone2", result)
    form.value.files2 = result
}
const handleFinish = (values) => {
    if (!form.value.id) {
        api.add(values).then(() => {
            onClose(true);
        })
    } else {
        values.id = form.value.id;
        api.edit(values).then(() => {
            onClose(true);
        })
    }
};
const emits = defineEmits(['OnClose'])
const onClose = (refresh) => {
    emits('OnClose', refresh)
};

const columns = [
    {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        width: 112,
    },
    {
        title: '物料编码',
        dataIndex: 'code',
        key: 'code',
        width: 150,
        align: 'center'

    },
    {
        title: '物料名称',
        dataIndex: 'name',
        key: 'name',
        width: 140,
        align: 'center'

    },
    {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        width: 100,
        align: 'center'

    },
    {
        title: '工程量',
        dataIndex: 'quantities',
        key: 'quantities',
        width: 120,
        align: 'center'

    },

    {
        title: '人工单价',
        dataIndex: 'laborUnitPrice',
        key: 'laborUnitPrice',
        width: 140,
        align: 'center'
    },
    {
        title: '人工合价',
        dataIndex: 'totalLaborCost',
        key: 'totalLaborCost',
        width: 140,
        align: 'center'
    },
    {
        title: '物料单价',
        dataIndex: 'unitPrice',
        key: 'unitPrice',
        width: 140,
        align: 'center'
    },
    {
        title: '预算单价',
        dataIndex: 'budgetUnitPrice',
        key: 'budgetUnitPrice',
        width: 140,
        align: 'center'
    },
    {
        title: '预算剩余',
        dataIndex: 'budgetRemain',
        key: 'budgetRemain',
        width: 140,
        align: 'center'
    },
    {
        title: '采购数量',
        dataIndex: 'num',
        key: 'num',
        width: 140,
        align: 'center'
    },
    {
        title: '采购金额',
        dataIndex: 'total',
        key: 'total',
        width: 140,
        align: 'center'
    },
    // {
    //     title: '物料合价',
    //     dataIndex: 'totalUnitPrice',
    //     key: 'totalUnitPrice',
    //     width: 140,
    //     align: 'center'
    // },
    // {
    //     title: '成本单价',
    //     dataIndex: 'costUnitPrice',
    //     key: 'costUnitPrice',
    //     width: 140,
    //     align: 'center'
    // },

    // {
    //     title: '成本总价',
    //     dataIndex: 'totalCost',
    //     key: 'totalCost',
    //     width: 140,
    //     align: 'center'
    // },
    // {
    //     title: '综合单价',
    //     dataIndex: 'synUnitPrice',
    //     key: 'synUnitPrice',
    //     width: 140,
    //     align: 'center'
    // },

    // {
    //     title: '综合总价',
    //     dataIndex: 'comTotalPrice',
    //     key: 'comTotalPrice',
    //     width: 140,
    //     align: 'center',
    //     customRender({ text, record, index, column }) {
    //         return `${record.comTotalPrice ?? ""}`;
    //     }
    // },
  
]
const supplierSelect = ref()
const onSupplier = () => {
    supplierSelect.value.show()
}
const supplierSelectOk = (selectRecords) => {

    form.value.supplierId = selectRecords[0].id;
    form.value.supplierName = selectRecords[0].supplierEntity == 1 ? selectRecords[0].companyName : selectRecords[0].name;

}

const proSelect = ref()
const onSearch = () => {
    proSelect.value.show()
}
const prSelectOk = (selectedRowKeys, selectRecords) => {
    console.log("项目选择ok ", selectedRowKeys, selectRecords)

    form.value.proId = selectRecords[0].id;
    form.value.proName = selectRecords[0].name;
    form.value.proCode = selectRecords[0].code;
    form.value.proSelectRecords = selectRecords;

    costApi.detail({ proId: form.value.proId }).then((res) => {
        console.log(" costApi.detail res:", res)
        mSelectOk(res.records)
    })
}
const mSelection = ref()
const addMaterial = () => {
    mSelection.value.show()
}

const remove = (index) => {
    form.value.purMaterialList.splice(index, 1)
}
const mSelectOk = (rows) => {
    // const selectedRows = JSON.parse(JSON.stringify(rows));
    // selectedRows.map(x => {
    //     x.totalCost = x.quantities * x.costUnitPrice
    //     x.comTotalPrice = x.quantities * x.comUnitPrice
    //     x.totalLaborCost = x.quantities * x.laborUnitPrice
    //     x.totalUnitPrice = x.quantities * x.unitPrice
    //     x.comTotalPrice = x.quantities * x.synUnitPrice


    // })

    const selectedRows = JSON.parse(JSON.stringify(rows));
    selectedRows.map(x => {
        // x.totalCost = x.quantities * x.costUnitPrice
        // x.comTotalPrice = x.quantities * x.comUnitPrice
        x.totalLaborCost = x.quantities * x.laborUnitPrice

        x.code=!x.code?x.material.code:x.code;
        x.name=!x.name?x.material.name:x.name;
        x.budgetDetailId = x.id
        x.budgetUnitPrice = 0
        x.budgetRemain = 0
        x.num = 1
        x.total = 0
        x.materialId = x.id
    })
    // if (selectedRows.length > 0) {
    //     var sumItem = { totalCost: 0, comTotalPrice: 0, totalLaborCost: 0, totalUnitPrice: 0, comUnitPrice: 0 }
    //     selectedRows.map(x => {
    //         sumItem.totalCost += x.totalCost
    //         sumItem.comTotalPrice += x.comTotalPrice
    //         sumItem.totalLaborCost += x.totalLaborCost
    //         sumItem.totalUnitPrice += x.totalUnitPrice
    //         sumItem.comUnitPrice += x.comUnitPrice
    //     })
    //     selectedRows.push(sumItem)
    // }
    form.value.purMaterialList = selectedRows
}


const show = (record) => {
    if (record) {
        form.value = { ...record }
        if (form.value) {
            form.value.files1 = form.value.files?.filter(x => x.type == 1)
            form.value.files2 = form.value.files?.filter(x => x.type == 2);//[{ type: 1, fileId: "11234", fileName: "11234.jpg" }]
        }
        costApi.detail({ proId: form.value.proId }).then((res) => {
            console.log(" costApi.detail res:", res)
            mSelectOk(res.records)
        })
    } else {
        form.value = {
        }
    }
}
const submit = () => {
    formRef.value.validate().then(() => {
        handleFinish(form.value)
    }).catch((err) => {

    });
}

// 重置
const resetForm = () => {
    formRef.value.resetFields()
}
defineExpose({
    getData,
    resetForm,
    show
})
</script>
